from django.core.management.base import BaseCommand
from django.db import connection, transaction
import os
from django.core.management import call_command
import io
class Command(BaseCommand):
    help = 'Init db data'

    def add_arguments(self, parser):
        parser.add_argument('--directory', type=str, help='The directory containing SQL files')

    def load_operation_from_sql(self):
        directory = 'sql/data/first'
        print(os.listdir(directory))
        sql_files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.sql')]

        # Create a migration operation for each SQL file
        operations = []
        for sql_file in sql_files:
            # Read the SQL code from the file
            with open(sql_file) as f:
                sql_code = f.read()
            # Create a migration operation for the SQL code
            operation = sql_code
            operations.append([operation,sql_file])
        return operations

    def handle(self, *args, **options):
        
        operations = self.load_operation_from_sql()
        
        with transaction.atomic():
            with connection.cursor() as cursor:
                for sql_code,filename in operations:
                    cursor.execute(sql_code)
                    self.stdout.write(self.style.SUCCESS(f"Proccessing: {filename} "))

        self.stdout.write(self.style.SUCCESS('Database data migrations complete.'))
        
         # Reset the database sequence
        self.stdout.write(self.style.SUCCESS('Resetting database sequences...'))
        # Get SQL commands from sqlsequencereset
        output = io.StringIO()
        call_command('sqlsequencereset', 'frontend_api', stdout=output, no_color=True)
        sql = output.getvalue()
        with connection.cursor() as cursor:
            cursor.execute(sql)

        self.stdout.write(self.style.SUCCESS('Database data migrations complete.'))